package com.toman.ui.data;


import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.tencent.smtt.sdk.QbSdk;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.CircleTransform;
import com.toman.Util.IntentUtils;
import com.toman.Util.NetworkUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.Util.XYMarkerView;
import com.toman.bean.DataBean;
import com.toman.bean.ItemDataBean;
import com.toman.ui.data.report.X5Activity;
import com.toman.ui.work.choose.ChooseCompanyListEmptyActivity;
import com.githang.statusbar.StatusBarCompat;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class DataFragment extends Fragment {

    public String mCompanyId;

    Unbinder unbinder;
    @BindView(R.id.lineChart)
    LineChart lineChart;

    ItemListAdapter adapterData;

    CommonAdapter<ItemDataBean> adapter;
    CommonAdapter<ItemDataBean> adapterChart;

    @BindView(R.id.gv_data)
    RecyclerView gvData;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.tv_data)
    TextView tvData;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_base)
    RelativeLayout rlBase;
    @BindView(R.id.iv_status)
    ImageView ivStatus;
    @BindView(R.id.bga_refresh)
    BGARefreshLayout bgaRefresh;
    @BindView(R.id.tv_title_line)
    TextView tvTitleLine;
    private List<ItemDataBean> listChart = new ArrayList<>();
    private List<ItemDataBean> listTitle = new ArrayList<>();
    DataBean dataBean;
private String token;
    private String urlDp;
    private String urlAppindex;
    public DataFragment() {
        // Required empty public constructor
    }

    View rootView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_data2,
                null);
        ButterKnife.bind(this, rootView);
        initFresh();



    }

    private void initFresh() {
        urlAppindex = "https://www.zjtmcloud.com:8090/appindex?index=";
        urlDp = "https://www.zjtmcloud.com:8090/appdp?id=";
//        urlAppindex="http://192.168.70.122:8005/appindex?index=";
//        urlDp="http://192.168.70.122:8005/appdp?id=";
        QbSdk.initX5Environment(getActivity(), new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
                //x5内核初始化完成回调接口，此接口回调并表示已经加载起来了x5，有可能特殊情况下x5内核加载失败，切换到系统内核。

            }

            @Override
            public void onViewInitFinished(boolean b) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.e("@@", "加载内核是否成功:" + b);
            }
        });
        QbSdk.initX5Environment(getActivity(), null);
        token = (String) SPUtils.get(getActivity(),"token","");

        bgaRefresh.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyApplication.getInstance(), false));

        bgaRefresh.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                if (NetworkUtils.checkNetState(getActivity())) {
                    // 如果网络可用，则加载网络数据
                    get();

                } else {
                    // 网络不可用，结束下拉刷新
                    bgaRefresh.endRefreshing();
                }
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                return false;
            }
        });


        DividerItemDecoration itemDecoration2 = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        itemDecoration2.setDrawable(getResources().getDrawable(R.drawable.ll_diver_vertical_none));
        lv.addItemDecoration(itemDecoration2);
    }

    private void initList() {
//        String items[] = new String[]{"接入产线数", "当日总产量", "当月总产量"};
//        for (int i = 0; i < items.length; i++) {
//            ItemDataBean bean = new ItemDataBean();
//            bean.setTitle(items[i]);
//            bean.setData(i + "00");
//            listChart.add(bean);
//        }
        initView();
        GridLayoutManager mgr = new GridLayoutManager(getActivity(), listTitle.size());
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        lv.setLayoutManager(manager);

        gvData.setLayoutManager(mgr);
        adapterChart.notifyDataSetChanged();
        adapter.notifyDataSetChanged();

    }

    private void initView() {
        mCompanyId = (String) SPUtils.get(getContext(), "cpy_id", "");


        adapter = new CommonAdapter<ItemDataBean>(getActivity(), R.layout.item_data, listTitle) {
            @Override
            protected void convert(ViewHolder holder, ItemDataBean item, int position) {
                holder.setText(R.id.tv_name, item.getTitle());
                holder.setText(R.id.tv_data, item.getData());
                if (position == listTitle.size() - 1) {
                    holder.getView(R.id.iv_line).setVisibility(View.GONE);
                }
            }
        };
        adapterChart = new CommonAdapter<ItemDataBean>(getActivity(), R.layout.item_chart, listChart) {
            @Override
            protected void convert(ViewHolder holder, ItemDataBean item, int position) {
                int[] status = {R.mipmap.data_icon_rise, R.mipmap.data_icon_decline, R.mipmap.data_icon_fair};
                holder.setText(R.id.tv_name, item.getTitle());
                holder.setText(R.id.tv_data, item.getData());
                ImageView iv = holder.getView(R.id.iv_icon);
                if (!StringUtils.isEmpty(item.getIcon())) {
                    Picasso.with(getActivity()).load(item.getIcon()).error(R.mipmap.my_icon_head).transform(new CircleTransform()).into(iv);
                }
                if (item.getDataStatus() != 3) {
                    try {
                        holder.setImageResource(R.id.iv_status, status[item.getDataStatus()]);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    holder.getView(R.id.iv_status).setVisibility(View.GONE);

                }
            }
        };
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<ItemDataBean> list = adapter.getDatas();
                ItemDataBean bean = list.get(position);
                Bundle bundle = new Bundle();

                appUpdata();
                if (mCompanyId.equals("1")) {
                    if (position == 0) {
                        bundle.putString("msg", "接入企业");
                        IntentUtils.startActivity(getActivity(), ChooseCompanyListEmptyActivity.class, bundle);

                    } else {
                        if (StringUtils.isEmpty(bean.getType())){
                            return;
                        }
                        bundle.putString("html", urlAppindex + bean.getType()+ "&token=" + token);

//                        bundle.putString("html", "http://192.168.70.122:8005/appindex?index=" + dataBean.getOee().getType());
                        IntentUtils.startActivity(getActivity(), X5Activity.class, bundle);
                    }
                } else {
                    if (StringUtils.isEmpty(bean.getType())){
                        return;
                    }
                    bundle.putString("html", urlDp + mCompanyId + "&index=" + bean.getType()+ "&token=" + token);

//                    bundle.putString("html", "http://192.168.70.122:8005/appdp?id="+ mCompanyId + "&index=" + bean.getType());
                    IntentUtils.startActivity(getActivity(), X5Activity.class, bundle);
                }


            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        gvData.setAdapter(adapter);
        lv.setAdapter(adapterChart);

        adapterChart.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<ItemDataBean> list = adapterChart.getDatas();
                ItemDataBean bean = list.get(position);
                if (StringUtils.isEmpty(bean.getType())){
                    return;
                }
                appUpdata();
                Bundle bundle = new Bundle();
                if (mCompanyId.equals("1")) {
                    bundle.putString("html", urlAppindex + bean.getType()+ "&token=" + token);
//                    bundle.putString("html", "http://192.168.70.122:8005/appindex?index=" + dataBean.getOee().getType());

                    IntentUtils.startActivity(getActivity(), X5Activity.class, bundle);
                } else {
//                    bundle.putString("html", "http://www.zjtmcloud.com/appdp?id=" + mCompanyId + "&index=" + bean.getType());
                    bundle.putString("html", urlDp + mCompanyId + "&index=" + bean.getType()+ "&token=" + token);

                    IntentUtils.startActivity(getActivity(), X5Activity.class, bundle);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });


    }

    private void initLine() {
        lineChart.setDrawGridBackground(false);
        lineChart.setNoDataTextColor(getResources().getColor(R.color.white));
        lineChart.setBorderColor(getResources().getColor(R.color.transparent));
        // no description text
        lineChart.getDescription().setEnabled(false);

        //设置显示类型，LINE CIRCLE SQUARE EM
        // enable touch gestures
        lineChart.setTouchEnabled(true);

        // enable scaling and dragging
        lineChart.setDragEnabled(false);
        lineChart.setScaleEnabled(true);
        // mChart.setScaleXEnabled(true);
        // mChart.setScaleYEnabled(true);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.getAxisLeft().setEnabled(false);
        ;
        lineChart.setDrawGridBackground(false);


        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(true);
    }

    public void line(String[] name, float[] content, String label) {
        initLine();


        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < content.length; i++) {
            if (i == content.length - 1) {
                yVals1.add(new Entry(i, content[i], getResources().getDrawable(R.drawable.circle_blue)));

            } else {
                yVals1.add(new Entry(i, content[i]));
            }
        }
        for (int i = 0; i < name.length; i++) {
            name[i] = name[i] + "月";
        }


//        int ssmax = (int) max;
        try {
            lineChart.setVisibility(View.VISIBLE);
            LineDataSet set1, set2, set3;

            if (lineChart.getData() != null &&
                    lineChart.getData().getDataSetCount() > 0) {
                set1 = (LineDataSet) lineChart.getData().getDataSetByIndex(0);

                set1.setValues(yVals1);


                LabelFormatter labelFormatter = new LabelFormatter(name);
                XAxis xAxis = lineChart.getXAxis();
//                xAxis.setLabelCount(str.length, true);

                xAxis.setValueFormatter(labelFormatter);
                lineChart.getData().notifyDataChanged();
                lineChart.notifyDataSetChanged();
                lineChart.animateXY(1000, 1000);

            } else {
                // create a dataset and give it a type
                set1 = new LineDataSet(yVals1, "");

                set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                set1.setColor(ColorTemplate.getHoloBlue());
//                set1.setCircleColor(ColorTemplate.getHoloBlue());
                set1.setFillColor(Color.WHITE);
                set1.setHighLightColor(Color.rgb(244, 117, 117));
                set1.setDrawCircleHole(false);
//                set1.setDrawCircles(true);
                set1.setColor(Color.WHITE);
                set1.setLineWidth(1.75f);
                set1.setCircleRadius(5f);
                set1.setCircleHoleRadius(2.5f);
                set1.setCircleColor(Color.WHITE);
                set1.setValueTextColor(Color.WHITE);
                set1.setHighLightColor(Color.WHITE);
                set1.setDrawValues(false);
                set1.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);

                //set1.setFillFormatter(new MyFillFormatter(0f));
                //set1.setDrawHorizontalHighlightIndicator(false);
                //set1.setVisible(false);
                //set1.setCircleHoleColor(Color.WHITE);

                // create a dataset and give it a type

                XAxis xAxis = lineChart.getXAxis();
                xAxis.setTextColor(Color.TRANSPARENT);
                xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
                xAxis.setLabelCount(content.length - 1, false);
                xAxis.setTextColor(Color.WHITE);

                xAxis.setDrawLabels(true);

                LabelFormatter labelFormatter = new LabelFormatter(name);
                xAxis.setValueFormatter(labelFormatter);
                XYMarkerView mv = new XYMarkerView(getContext(), labelFormatter);
                mv.setChartView(lineChart); // For bounds control
                lineChart.setMarker(mv); //
                // create a data object with the datasets
                LineData data = new LineData(set1);
                data.setValueTextColor(Color.WHITE);
                data.setValueTextSize(9f);
                // set data
                lineChart.setData(data);
                lineChart.animateXY(1000, 1000);

            }


        } catch (Exception e) {
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.button_blue), false);
        MobclickAgent.onPageStart("数据页"); //统计页面，"MainScreen"为页面名称，可自定义
        try {
            get();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void appUpdata() {
        OkHttpUtils
                .get(NewBaseUrl.app_update)
                .params("token", (String) SPUtils.get(getActivity(), "token", ""))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        try {
                            org.json.JSONObject js = new org.json.JSONObject(result);
                            int code = js.getInt("code");
                            ViewUtil.lagout(code,getActivity());

                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("数据页");
    }

    private void setOeeImg(DataBean bean) {
        switch (bean.getOee().getDataStatus()) {
            case 0:
                ivStatus.setImageResource(R.mipmap.data_icon_oee_rise);
                break;
            case 1:
                ivStatus.setImageResource(R.mipmap.data_icon_oee_decline);
                break;
            case 2:
                ivStatus.setImageResource(R.mipmap.data_icon_oee_fair);
                break;
            case 3:
                ivStatus.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.i("test", "AFragment-->onCreateView");
        ViewGroup perentView = (ViewGroup) rootView.getParent();
        if (perentView != null) {
            perentView.removeAllViewsInLayout();
        }
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    //    @OnClick(R.id.tv_oee_num)
//    public void onViewClicked() {
//        IntentUtils.startActivity(getActivity(), ReportCompanyActivity.class);
//    }
    public void get() {
        String token = (String) SPUtils.get(getActivity(), "token", "");
        OkHttpUtils
                .get(NewBaseUrl.indexData)
                .params("token", token)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "数据详情: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getActivity());
                        ViewUtil.lagout(code, getActivity());
                        if (code == 0) {
                            try {
                                dataBean = (DataBean) JSON.parseObject(jsonObj.getString("data"), DataBean.class);
                                tvData.setText(dataBean.getOee().getData());
                                tvTitle.setText(dataBean.getOee().getTitle());
                                setOeeImg(dataBean);
                                listTitle = dataBean.getTitleList();
                                listChart = dataBean.getChartList();

                                String[] name = dataBean.getLineChart().getX().split(",");
                                String[] content1 = (dataBean.getLineChart().getY().split(","));
                                float[] content = new float[content1.length];
                                for (int i = 0; i < content1.length; i++) {
                                    content[i] = Float.parseFloat(content1[i]);
                                }
                                tvTitleLine.setText(dataBean.getLineChart().getName());
                                line(name, content, dataBean.getLineChart().getName());
                                initList();
                                if (bgaRefresh != null) {
                                    bgaRefresh.endRefreshing();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.makeText(getActivity(), jsonObj.getString("msg"));
                        }
                        if (bgaRefresh != null) {
                            bgaRefresh.endRefreshing();
                        }

                    }
                });
    }

    @OnClick(R.id.tv_data)
    public void onViewClicked() {
        Bundle bundle = new Bundle();
        if (StringUtils.isEmpty(dataBean.getOee().getType())){
            return;
        }
        if (mCompanyId.equals("1")) {
//            bundle.putString("html", "http://www.zjtmcloud.com/appindex?index=" + dataBean.getOee().getType());
            bundle.putString("html", urlAppindex + dataBean.getOee().getType()+ "&token=" + token);

            IntentUtils.startActivity(getActivity(), X5Activity.class, bundle);
        } else {
            bundle.putString("html", urlDp + mCompanyId + "&index=" + dataBean.getOee().getType()+ "&token=" + token);
//            bundle.putString("html", "http://www.zjtmcloud.com/appdp?id=" + mCompanyId + "&index=" + dataBean.getOee().getType());

            IntentUtils.startActivity(getActivity(), X5Activity.class, bundle);
        }

    }
    class LabelFormatter implements IAxisValueFormatter {
        private final String[] mLabels;

        public LabelFormatter(String[] labels) {
            mLabels = labels;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            try {
                return mLabels[(int) value];
            } catch (Exception e) {
                e.printStackTrace();
                return mLabels[0];
            }

        }
    }
}
